package com.ysd.ziyuanshiyongtongji.service;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.ysd.ziyuanshiyongtongji.dao.IReadRoomDao;
import com.ysd.ziyuanshiyongtongji.dto.ReadRoomDTO;
import com.ysd.ziyuanshiyongtongji.model.ReadRoom;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

/**
 * ReadRoomServiceImpl
 */
@Service
public class ReadRoomServiceImpl implements IReadRoomService {
    @Resource
    private IReadRoomDao readRoomDao;

    @Override
    public Page<ReadRoom> findPage(ReadRoomDTO dto) {
        Sort sort = Sort.by(Sort.Order.asc("id"));
        Pageable page = PageRequest.of((dto.getPage() - 1) * dto.getLimit(), dto.getLimit(), sort);
        return readRoomDao.findAll(getWhereClause(dto),page);
    }

    private Specification<ReadRoom> getWhereClause(final ReadRoomDTO dto) {
        return new Specification<ReadRoom>() {

            @Override
            public Predicate toPredicate(Root<ReadRoom> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate p = criteriaBuilder.conjunction();
                List<Expression<Boolean>> exList = p.getExpressions();
                if (dto.getName() != null && !"".equals(dto.getName())) {
                    exList.add(criteriaBuilder.like(root.<String>get("name"), "%" + dto.getName() + "%"));
                }
                
                return p;
            }
        };
    }

    @Override
    public ReadRoom saveReadRoom(ReadRoom r) {     
        return readRoomDao.save(r);
    }

    @Override
    public void del(Integer id) {
      readRoomDao.deleteById(id);
    }
    @Override
    public List<ReadRoom> findAll() {    
        return readRoomDao.findAll();
    }

    @Override
    public void deletebatch(List<Integer> ids) {
      readRoomDao.deletebatch(ids);
    }

}